<?php

namespace app\company\controller;

use app\admin\model\Communitys;
use app\admin\model\express\Companys;
use app\admin\model\money\Change;
use app\admin\model\product\Category;
use app\admin\model\product\Listo;
use app\admin\model\product\Lists;
use app\admin\model\product\Order;
use app\admin\model\Transport;
use app\admin\model\user\Returns;
use app\common\controller\Api;
use app\common\controller\CompanyApi;
use app\common\controller\Kd100;
use think\Db;
use think\Exception;
use think\Request;

class Userreturns extends CompanyApi
{
    protected static $model = null;
    protected $noNeedLogin = [''];
    protected $noNeedRight = '*';

    public function __construct(Request $request = null)
    {
        parent::__construct($request);
        self::$model = new Returns();
    }

    /**
     * 获取商品清单表
     */
    public function lists()
    {
        $pageSize = $this->request->post('page_size', 15);
        $user = $this->auth->getUser();
        $department_id = $user->department_id;
        $cateIds = Category::where('department_id', $department_id)->column('id');
        $ids = Lists::where('category_id', 'in', $cateIds)->column('id');
        $where = [
            'product_id' => ['in', $ids],
            'status' => ['>=', 1]
        ];

        $lists = self::$model
//            ->field('listo.id,tag,product_id,product_name,num,price,parameters,listo.pay_time')
            ->where($where)
            ->order('id desc')
            ->paginate($pageSize);

        foreach ($lists as &$val) {
            $pInfo = Lists::where('id', $val['product_id'])->find();
            $val['name'] = $pInfo['name'];
            $val['image'] = make_full_url($pInfo['image']);
            $val['intro'] = $pInfo['intro'];
        }

        $this->success('申请列表！', $lists);
    }

    public function read()
    {
        $id = $this->request->post('id');
        if (!$id) {
            $this->error('参数缺失！');
        }
        $row = self::$model->find($id);
        if (!$row) {
            $this->error('该申请不存在！');
        }

        $row->reply_image = make_full_url($row->reply_image);
        $row->review_image1 = make_full_url($row->review_image1);
        $row->review_image2 = make_full_url($row->review_image2);

        $user = \app\admin\model\User::field('username,nickname')->find($row->user_id);
        $row->user = $user;

        $user1 = \app\admin\model\department\User::field('username,nickname')->find($row->review_id1);
        $row->user1 = $user1;

        $user2 = \app\admin\model\department\User::field('username,nickname')->find($row->review_id2);
        $row->user2 = $user2;

        $this->success('登记详情', $row);
    }

    /**
     * 管理员审核
     */
    public function audit()
    {
        $id = input('id');
        $orderInfo = self::$model->where('id', $id)->find();
        if (!$orderInfo) {
            $this->error('该申请单不存在！');
        }

        if ($orderInfo->status != 1) {
            $this->error('该申请单不可审核！');
        }

        $userId = $this->auth->id;
        $plInfo = Lists::where('id', $orderInfo->product_id)->find();
        $ret = $this->checkAuth($userId, $plInfo->category_id);
        if ($ret['code'] == 0) {
            $this->error($ret['msg']);
        }

        $review_image = $this->request->post('review_image1');
        $review_remark = $this->request->post('review_remark1');
        $status = $this->request->post('status');
        if (!$review_image) {
            $this->error('审核人员必须签名！');
        }

        if (!in_array($status, [5, 10])) {
            $this->error('审核错误！');
        }

        $community_id = \app\common\model\User::where('id', $orderInfo->user_id)->value('community_id');
        $ulInfo = \app\admin\model\user\Lists::where('product_id', $orderInfo->product_id)
            ->where('community_id', $community_id)
            ->find();
        if ($status == 10 && $ulInfo->stock < $orderInfo->num) {
            $this->error('该物品余量已不足！');
        }

        Db::startTrans();
        try {

            $orderInfo->review_id1 = $userId;
            $orderInfo->review_image1 = $review_image;
            $orderInfo->review_remark1 = $review_remark;
            $orderInfo->send_time = time();
            $orderInfo->status = $status;
            $ret = $orderInfo->save();

            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }

        if (!$ret) {
            $this->error('审核失败');
        }

        $this->success('审核成功！');
    }

    /**
     * 领导复核
     */
    public function review()
    {
        $id = input('id');
        $orderInfo = self::$model->where('id', $id)->find();
        if (!$orderInfo) {
            $this->error('该申请单不存在！');
        }

        if ($orderInfo->status != 10) {
            $this->error('该申请单不可审核！');
        }

        $userId = $this->auth->id;
        $plInfo = Lists::where('id', $orderInfo->product_id)->find();
        $ret = $this->checkLeaderAuth($userId, $plInfo->category_id);
        if ($ret['code'] == 0) {
            $this->error($ret['msg']);
        }

        $review_image = $this->request->post('review_image2');
        $review_remark = $this->request->post('review_remark2');
        $status = $this->request->post('status');
        if (!$review_image) {
            $this->error('审批领导必须签名！');
        }

        if (!in_array($status, [15, 20])) {
            $this->error('审核错误！');
        }

        $community_id = \app\common\model\User::where('id', $orderInfo->user_id)->value('community_id');
        $ulInfo = \app\admin\model\user\Lists::where('product_id', $orderInfo->product_id)
            ->where('community_id', $community_id)
            ->find();
        if ($status == 20 && $ulInfo->stock < $orderInfo->num) {
            $this->error('该物品余量已不足！');
        }

        Db::startTrans();
        try {

            $orderInfo->review_id2 = $userId;
            $orderInfo->review_image2 = $review_image;
            $orderInfo->review_remark2 = $review_remark;
            $orderInfo->finish_time = time();
            $orderInfo->status = $status;
            $ret = $orderInfo->save();

            if ($status == 20) {
                $ulInfo->stock -= $orderInfo->num;
                $ulInfo->save();

                $plInfo->stock += $orderInfo->num;
                $plInfo->save();

                $orderNum = create_order($id);
                $change_type = 4;
                $department_id = Category::where('id', $plInfo->category_id)->value('department_id');
                $mdata = [
                    'order_num' => $orderNum,
                    'record_type' => 1,
                    'product_id' => $orderInfo->product_id,
                    'change_type' => $change_type,
                    'moneytype' => $plInfo->type,
                    'number' => $orderInfo->num,
                    'hasnumber' => $plInfo->stock,
//                'remark' => $tag,
                    'user_id' => $orderInfo->community_id,
                    'relation_id' => $id,
                    'targetuserid' => $department_id
                ];

                Change::create($mdata);
            }

            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }

        if (!$ret) {
            $this->error('审批失败');
        }

        $this->success('审批成功！');
    }

    // 超级管理员

    /**
     * 获取商品清单表
     */
    public function index()
    {
        $userId = $this->auth->id;
        $user = $this->auth->getUser();
        if ($user->is_manager != 1) {
            $this->error('非法操作！');
        }
        $pageSize = $this->request->post('page_size', 15);
        $community_id = $this->request->post('community_id');
        if (!$community_id) {
            $this->error('参数缺失！');
        }
        $where = [
            'user_id' => $userId,
            'community_id' => $community_id
        ];

        $lists = self::$model
            ->where($where)
            ->order('id desc')
            ->paginate($pageSize);

        foreach ($lists as &$val) {
            $pInfo = Lists::where('id', $val['product_id'])->find();
            $val['name'] = $pInfo['name'];
//            $val['cover_ico'] = make_full_url($pInfo['image']);
//            $val['intro'] = $pInfo['intro'];
        }

        $this->success('归还列表！', $lists);
    }

    /**
     * 社区管理员申请
     */
    public function create()
    {
        $user = $this->auth->getUser();
        if ($user->is_manager != 1) {
            $this->error('非法操作！');
        }
        $id = input('id');
        $num = input('num');
        $reply_image = input('reply_image');
        $reply_remark = input('reply_remark');
        if (!$id || !$num || !$reply_image) {
            $this->error('参数缺失！');
        }
        $userId = $this->auth->id;
        $pInfo = \app\admin\model\user\Lists::where('id', $id)
            ->find();
        if (!$pInfo) {
            $this->error('仓库中无该物资！');
        }
        if ($pInfo->type != 2) {
            $this->error('该物资不用归还！');
        }
        if ($pInfo->stock < $num) {
            $this->error('仓库中库存不足！');
        }

        $rdata = [
            'community_id' => $pInfo->community_id,
            'product_id' => $pInfo->product_id,
            'num' => $num,
            'user_id' => $userId,
            'reply_image' => $reply_image,
            'reply_remark' => $reply_remark,
            'pay_time' => time(),
            'status' => 1
        ];

        $ret = Returns::create($rdata);
        if (!$ret) {
            $this->error('申请失败！');
        }

        $this->success('申请成功！');
    }


}